package com.example.everying.utils;/*
 * 项目名称: everything
 * 文件名: QueryLocationUtil
 * 作者: 张泽阳
 * 日期: 2025/6/3
 * 描述:
 */

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class QueryLocationUtil {
    @Value("${ipKey}")
    private String ipKey;
    @Autowired
    private RestTemplate restTemplate;
    private final String DATATYPE = "jsonp";
    public String queryLocation(String ip) {
        String url = "https://api.ip138.com/ipdata/?ip=" + ip + "&datatype="+DATATYPE;
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("token", ipKey);
            return execution.execute(request, body);
        });
        String forObject = restTemplate.getForObject(url, String.class);
/*        String url = "https://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip;
        String str = restTemplate.getForObject(url, String.class);*/
        JSONObject obj = (JSONObject) JSON.parse(forObject);
        String pro = obj.getString("data").split(",")[1];
        if (pro == null){
            pro = "未知";
        }
        if (pro.startsWith("\"")  && pro.endsWith("\""))  {
            pro = pro.substring(1,  pro.length()  - 1); // 去掉首尾的双引号
        }
        return pro;
    }
}
